package com.liuyi.framework.web.jackson;

import cn.hutool.core.date.DatePattern;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName : ConverterSerializerConfig  //类名
 * @Description : Springboot入参类型转换
 * <p>
 * 不要转 lambda表达式 否则启动失败
 * </p>
 * @Author : Mr.Fmy  //作者
 * @Date: 2020-07-22 17:40  //时间
 */
public class ConverterSerializerConfig {

    /**
     * String --> LocalDatetime
     */
    /**
     * LocalDateTime转换器，用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        };
    }

    /**
     * String --> LocalDate
     */
    //@Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(@NotNull String source) {
                if (StringUtils.hasText(source)) {
                    return LocalDate.parse(source, DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                }
                return null;
            }
        };
    }
}
